/*
 * @lc app=leetcode.cn id=100 lang=csharp
 *
 * [100] 相同的树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public bool IsSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null)
        {
            return true;
        }
        if(p == null || q == null)
        {
            return false;
        }
        var queueP = new Queue<TreeNode>();
        queueP.Enqueue(p);
        var queueQ = new Queue<TreeNode>();
        queueQ.Enqueue(q);
        while(queueP.Count > 0 && queueQ.Count > 0)
        {
            var nodeP = queueP.Dequeue();
            var nodeQ = queueQ.Dequeue();
            if(nodeP.val != nodeQ.val) return false;
            TreeNode pLeft = nodeP.left, pRight = nodeP.right, qLeft = nodeQ.left, qRight = nodeQ.right;
            if ((pLeft == null ^ qLeft == null) || (pRight == null ^ qRight == null))
            {
                return false;
            }
            if( pLeft != null)
            {
                queueP.Enqueue(pLeft);
            }
            if( pRight != null)
            {
                queueP.Enqueue(pRight);
            }
            if( qLeft != null)
            {
                queueQ.Enqueue(qLeft);
            }
            if( qRight != null)
            {
                queueQ.Enqueue(qRight);
            }
            
        }
        return queueP.Count == 0 && queueQ.Count == 0;
    }
}
// @lc code=end

